﻿using System;
using System.IO;
using System.Text;

namespace WPFNote.Utilities.Common;

public class BinFileHelper
{
    private const int RandomArrLen = 1999;
    public bool Write(string filePath, string content)
    {
        try
        {
            // 将字符串转换为字节序列  
            var stringBytes = Encoding.UTF8.GetBytes(content);  
  
            // 生成一些随机字节，用于混淆  
            var randomBytes = new byte[RandomArrLen];  
            var rng = new Random();  
            rng.NextBytes(randomBytes);  
  
            // 将随机字节、字符串字节和更多随机字节合并成一个数组  
            var combinedBytes = new byte[randomBytes.Length + stringBytes.Length + randomBytes.Length];  
            Buffer.BlockCopy(randomBytes, 0, combinedBytes, 0, randomBytes.Length);  
            Buffer.BlockCopy(stringBytes, 0, combinedBytes, randomBytes.Length, stringBytes.Length);  
            Buffer.BlockCopy(randomBytes, 0, combinedBytes, randomBytes.Length + stringBytes.Length, randomBytes.Length); 
            
            // 将合并后的字节序列写入二进制文件  
            WriteBinaryFile(filePath, combinedBytes);  
            return true;
        }
        catch
        {
            return false;
        }
    }
    

    public string Read(string filePath)
    {
        try
        {
            // 从二进制文件中读取并解析字符串  
            var readBytes = ReadBinaryFile(filePath);  
            // 跳过开头的随机字节，并提取字符串字节  
            var actualStringBytes = new byte[readBytes.Length - RandomArrLen*2];  
            Buffer.BlockCopy(readBytes, RandomArrLen, actualStringBytes, 0, actualStringBytes.Length);  
            var message = Encoding.UTF8.GetString(actualStringBytes);  
            return message;
        }
        catch
        {
            return string.Empty;
        }
    }
    
    private void WriteBinaryFile(string filePath, byte[] bytes)
    {
        using var fs = new FileStream(filePath, FileMode.Create);
        fs.Write(bytes, 0, bytes.Length);
    }
    
    private byte[] ReadBinaryFile(string filePath)  
    {
        using var fs = new FileStream(filePath, FileMode.Open);
        using var br = new BinaryReader(fs);
        var bytes = br.ReadBytes((int)fs.Length);
        return bytes;  
    }
}